import { useMemo, useState } from 'react'
import type { FormEvent } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import dayjs from 'dayjs'

import Modal from './Modal'
import { CycleAPI } from '../app/api'
import { FormField, Input, Textarea } from './ui/Form'

const createInitialState = () => ({
  startDate: dayjs().format('YYYY-MM-DD'),
  endDate: '',
  status: '',
  notes: '',
})

type CycleLogDialogProps = {
  open: boolean
  onClose: () => void
}

const CycleLogDialog = ({ open, onClose }: CycleLogDialogProps) => {
  const queryClient = useQueryClient()
  const [form, setForm] = useState(() => createInitialState())
  const [error, setError] = useState<string | null>(null)

  const mutation = useMutation({
    mutationFn: CycleAPI.createLog,
    onSuccess: async () => {
      await Promise.all([
        queryClient.invalidateQueries({ queryKey: ['cycle', 'logs'] }),
        queryClient.invalidateQueries({ queryKey: ['cycle', 'predictions'] }),
      ])
      setForm(createInitialState())
      onClose()
    },
  })

  const isValid = useMemo(() => Boolean(form.startDate), [form.startDate])

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    if (!isValid || mutation.isPending) return
    setError(null)

    try {
      await mutation.mutateAsync({
        start_date: form.startDate,
        end_date: form.endDate || undefined,
        symptoms: form.status ? { state: form.status } : undefined,
        notes: form.notes || undefined,
      })
    } catch (err) {
      const message = err instanceof Error ? err.message : '保存失败，请稍后重试'
      setError(message)
    }
  }

  return (
    <Modal open={open} onClose={onClose} title="记录生理期">
      <form className="space-y-4" onSubmit={handleSubmit}>
        <div className="grid gap-3 sm:grid-cols-2">
          <FormField label="开始日期" required>
            <Input
              type="date"
              value={form.startDate}
              onChange={(e) => setForm((prev) => ({ ...prev, startDate: e.target.value }))}
              max={form.endDate || undefined}
            />
          </FormField>
          <FormField label="结束日期">
            <Input type="date" value={form.endDate} onChange={(e) => setForm((prev) => ({ ...prev, endDate: e.target.value }))} min={form.startDate || undefined} />
          </FormField>
        </div>
        <FormField label="身体状态" hint="例如：轻微不适、情绪波动等">
          <Input
            value={form.status}
            onChange={(e) => setForm((prev) => ({ ...prev, status: e.target.value }))}
            placeholder="如：轻微不适、情绪波动等"
          />
        </FormField>
        <FormField label="备注">
          <Textarea
            value={form.notes}
            onChange={(e) => setForm((prev) => ({ ...prev, notes: e.target.value }))}
            placeholder="记录饮食、体温或需要关注的细节"
          />
        </FormField>
        {error ? <p className="text-xs text-red-500">{error}</p> : null}
        <button
          type="submit"
          className="w-full rounded-full bg-gradient-to-r from-blush-500 to-sky-500 px-6 py-3 text-sm font-semibold text-white shadow-card transition hover:shadow-lg disabled:cursor-not-allowed disabled:opacity-60"
          disabled={!isValid || mutation.isPending}
        >
          {mutation.isPending ? '保存中...' : '保存记录'}
        </button>
      </form>
    </Modal>
  )
}

export default CycleLogDialog
